<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="图片名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入视频名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="分类" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="视频分类"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in typeArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="视频状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in statusArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="swiperList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="视频名称"
        prop="title"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="上传者"
        prop="createBy"
        align="center"
        :show-overflow-tooltip="true"
        width="150"
      />

      <el-table-column label="轮播" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isExhibition"
            :active-value="true"
            :inactive-value="false"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="图片描述"
        prop="remark"
        align="center"
        :show-overflow-tooltip="true"
        width="190"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:role:edit']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :visible.sync="dialogStatus.isCropDialogShow"
      title="图片裁剪"
      center
      width="900"
    >
      <div style="width: 100%; height: 60vh">
        <vue-cropper
          ref="cropper"
          :img="options.img"
          :autoCropWidth="options.autoCropWidth"
          :autoCropHeight="options.autoCropHeight"
          :fixedNumber="options.fixedNumber"
          :centerBox="options.centerBox"
          :canScale="options.canScale"
          :infoTrue="options.infoTrue"
          :auto-crop="options.autoCrop"
          :fixed-box="options.fixedBox"
          :fixed="options.fixed"
          :info="false"
          @realTime="realTimeCrop"
        >
        </vue-cropper>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogStatus.isCropDialogShow = false"
            >取消</el-button
          >
          <el-button @click="cropperRef.refresh()">重置</el-button>
          <el-button type="primary" @click="finishCrop"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 新增轮播图 -->
    <el-dialog
      :visible.sync="dialogStatus.visible"
      :title="dialogStatus.title"
      width="40%"
      center
      :show-close="false"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form
        ref="form"
        :model="dialogData"
        :rules="rules"
        label-width="100px"
        v-loading="dialogLoading"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            :disabled="dialogStatus.isDetail"
            v-model="dialogData.title"
            placeholder="请输入轮播图标题"
          />
        </el-form-item>
        <el-form-item label="是否轮播" prop="isExhibition">
          <el-select
            :disabled="dialogStatus.isDetail"
            v-model="dialogData.isExhibition"
            placeholder="请选择"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in commonArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            :disabled="dialogStatus.isDetail"
            v-model="dialogData.remark"
            placeholder="请输入轮播图标题"
            type="textarea"
          />
        </el-form-item>

        <el-form-item label="绑定图片" prop="" v-if="dialogStatus.isDetail">
          <div style="width: 150px; height: 195px">
            <img
              :src="dialogData.linkUrl"
              alt=""
              style="width: 100%; height: 100%; object-fit: cover"
            />
          </div>
        </el-form-item>

        <el-form-item label="图片上传" prop="title" v-else>
          <el-upload
            ref="uploadRef"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="beforeUpload"
          >
            <!-- :limit="1"
            :on-exceed="onExceed" -->
            <div style="width: 100%; height: 100%; position: relative">
              <div v-if="fileUrl" style="width: 100%; height: 100%">
                <img
                  style="
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    object-fit: scale-down;
                  "
                  :src="fileUrl"
                  alt="label-preview"
                />
              </div>
              <div
                style="
                  width: 100%;
                  height: 100%;
                  display: flex;
                  justify-content: center;
                  margin: 60px 0 0 0px;
                "
                v-else
              >
                <i class="el-icon-picture"></i>
              </div>
            </div>
          </el-upload>

          <div style="display: flex; margin: 10px 0 0 0vw">
            <el-button
              type="text"
              :disabled="!dialogStatus.isCrop"
              @click="handleUpload"
              >上传
            </el-button>
            <el-button
              type="text"
              :disabled="!dialogStatus.isSelected"
              @click="handlePictureCardPreview"
              >查看
            </el-button>

            <!-- <el-button link icon="UploadFilled">重传</el-button> -->
            <div
              v-show="isFinishUpload"
              style="color: green; margin-left: 20px"
            >
              已成功上传√
            </div>
          </div>
          <div v-if="isUpload" style="color: green">上传成功！</div>
          <div v-else>未上传</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitForm">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
    <div>
      <ElImageViewer
        v-if="dialogVisible"
        :url-list="[dialogImageUrl]"
        teleported
        :on-close="handleClosePreview"
        :z-index="9999"
      />
    </div>
  </div>
</template>

<script>
import {
  getSwiperList as getSwiperListApi,
  postToOss as postToOssApi,
  addSwiper as addSwiperApi,
  updateSwiper as updateSwiperApi,
  deleteSwiper as deleteSwiperApi,
} from "../../../api/video/swiper";
import { Notification, MessageBox, Message, Loading } from "element-ui";
// 引入截图插件
import { VueCropper } from "vue-cropper";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import to from "await-to-js";
export default {
  name: "videoList",
  components: {
    ElImageViewer,
    VueCropper,
  },
  data() {
    return {
      queryParams: {
        title: "",
        isExhibition: "",
        pageSize: 10,
        pageNum: 1,
        orderByColumn: "createTime",
        isAsc: "desc",
      },
      // 多选
      multiple: true,
      // 单选状态
      single: true,
      ids: [],
      // 是否展示search
      showSearch: true,
      // 加载状态
      loading: false,
      dialogLoading: false,
      // 轮播图列表
      swiperList: [],
      // 列表总数
      total: 0,
      // 将要上传的文件
      file: "",
      fileList: [],
      fileName: "",
      // 视频上传进度
      percentage: 0,
      // 视频播放器
      videoPlayer: "",
      initDialogStatus: {
        isDetail: false,
        isUpdate: false,
        isAdd: false,
        visible: false,
        isUploading: false,
        isSelected: false,
        isCrop: false,
        title: "",
        isCropDialogShow: false,
      },
      dialogStatus: {
        isDetail: false,
        isUpdate: false,
        isAdd: false,
        visible: false,
        isUploading: false,
        isCropDialogShow: false,
        isSelected: false,
        isCrop: false,
        title: "",
      },
      dialogData: {
        // 标题
        title: "",
        // 备注
        remark: "",
        type: "",
        fileName: "",
        status: "0",
        // 是否轮播
        isExhibition: true,
        linkUrl: "",
      },
      typeArr: [
        {
          label: "option1",
          value: "1",
        },
        {
          label: "option2",
          value: "2",
        },
        {
          label: "option3",
          value: "3",
        },
      ],
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      isUpload: false,
      commonArr: [
        {
          label: "是",
          value: true,
        },
        {
          label: "否",
          value: false,
        },
      ],
      rules: {
        title: [
          { required: true, message: "视频标题不能为空！", trigger: "blur" },
        ],
        status: [
          { required: true, message: "状态为必选项！", trigger: "blur" },
        ],
      },
      // 截图框相关配置
      options: {
        img: "", // 需要剪裁的图片
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 509, // 默认生成截图框的宽度
        autoCropHeight: 340, // 默认生成截图框的长度
        fixedBox: true, // 是否固定截图框的大小 不允许改变
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量 [1至0.1]
        outputType: "jpeg", // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        // fixed: true, // 是否开启截图框宽高固定比例
        // fixedNumber: [200, 300], // 截图框的宽高比例 需要配合centerBox一起使用才能生效
        full: false, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        // centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
        enlarge: 2,
      },
    };
  },
  methods: {
    // 重置
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 搜索
    handleQuery() {
      this.getList();
    },
    // 获取列表
    async getList() {
      console.log(1);
      this.loading = true;
      const [err, res] = await to(getSwiperListApi(this.queryParams));
      if (!err) {
        console.log(res);
        this.swiperList = res.rows;
        this.total = Number(res.total);
        this.loading = false;
      } else {
        Message.error("获取轮播图列表失败");
        this.loading = false;
      }
    },
    // 获取资源详情
    // async getSwiperDetail(id) {
    //   const [err, res] = await to(getVideoDetailApi(id));
    //   if (!err) {
    //     console.log(res);
    //     this.dialogData = res.data;
    //   }
    // },
    // 点击视频详情按钮
    async handleDetail(row) {
      this.dialogStatus.visible = true;
      this.dialogStatus.isDetail = true;
      this.dialogStatus.title = "图片详情";
      // 获取视频详情
      // await this.getSwiperDetail(row.videoId);
      this.dialogData = row;
    },
    // 添加视频按钮
    handleAdd() {
      this.dialogStatus.visible = true;
      this.dialogStatus.isAdd = true;
      this.dialogStatus.title = "新增视频";
    },
    // 修改视频按钮
    async handleUpdate(row) {
      this.dialogStatus.visible = true;
      this.dialogStatus.isUpdate = true;
      this.dialogStatus.title = "更新视频";
      // let _id;
      // if (row.videoId) {
      //   _id = row.videoId;
      // } else {
      //   _id = this.ids[0];
      // }
      if (row.linkUrl && row.linkUrl != "") {
        this.fileUrl = row.linkUrl;
        this.dialogStatus.isSelected = true;
        this.dialogStatus.isCrop = false;
        this.isUpload = true;
      }
      // this.dialogData.title = row.title;
      // this.dialogData.bannerId = row.bannerId
      // this.dialogData.isExhibition = row.isExhibition
      // this.dialogData.remark = row.remark
      // this.dialogData.linkUrl = row.linkUrl
      this.dialogData = row;
      console.log(row, this.dialogData.linkUrl);
    },
    // 修改视频状态
    async handleStatusChange(row) {
      console.log(row);
      this.loading = true;
      row.status === "1" ? "0" : "1";
      const [err, res] = await to(updateVideoApi(row));
      if (!err) {
        // 更新成功
        console.log(res);
        Message.success("更改成功");
        this.getList();
        this.loading = false;
      } else {
        Message.error("更改失败");
        this.getList();
        this.loading = false;
      }
    },
    // 删除按钮
    async handleDelete(row) {
      this.loading = true;
      console.log(row);
      const message =
        row.bannerId === undefined || null
          ? "是否确认删除已勾选的数据项"
          : '是否确认删除视频编号为"' + row.title + '"的数据项?';
      const [err, res] = await to(
        this.$confirm(message, "提示", {
          confirmButtonText: "确定",
          handleCancelButtonText: "取消",
          type: "warning",
        })
      );
      if (!err) {
        if (row.bannerId) {
          const [err] = await to(deleteSwiperApi(row.bannerId));
          if (!err) {
            Message.success("删除成功");
            this.getList();
            this.loading = false;
          } else {
            Message.error("删除失败");
            this.getList();
            this.loading = false;
          }
        } else {
          const [err] = await to(deleteSwiperApi(this.ids));
          if (!err) {
            Message.success("删除成功");
            this.getList();
            this.loading = false;
          } else {
            Message.error("删除失败");
            this.getList();
            this.loading = false;
          }
        }
      } else {
        Message.info("取消成功");
        this.loading = false;
      }
    },
    // 列表勾选
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.videoId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      console.log(this.ids);
    },
    // dialog提交按钮
    handleSubmitForm() {
      this.$refs["form"].validate(async (vilid) => {
        if (vilid) {
          if (this.dialogData.bannerId) {
            // 有id为更新
            if (!this.isUpload) {
              Message.info("您还未上传图片，请先上传图片！");
            } else {
              const [err] = await to(updateSwiperApi(this.dialogData));
              if (!err) {
                // 更新成功
                Message.success("更新成功");
                await this.getList();
                this.dialogStatus.visible = false;
              } else {
                Message.error("更新失败");
                await this.getList();
              }
            }
          } else {
            // 无id为新增
            if (!this.isUpload) {
              Message.info("您还未上传图片，请先上传图片！");
            } else {
              console.log(this.dialogData);
              this.dialogStatus.isUploading = true;
              const [err] = await to(addSwiperApi(this.dialogData));
              if (!err) {
                Message.success("新增成功");
                await this.getList();
                this.dialogStatus.visible = false;
              } else {
                Message.error("新增失败");
                await this.getList();
              }
            }
          }
        }
      });
    },
    // 取消按钮
    handleCancel() {
      this.dialogStatus.visible = false;
    },
    // 关闭dialog
    closeDialog() {
      this.loading = false;
      this.dialogStatus = Object.assign({}, this.initDialogStatus);
      this.dialogData = {
        // 标题
        title: "",
        // 备注
        remark: "",
        type: "",
        fileName: "",
        status: "0",
        // 是否轮播
        isExhibition: true,
      };
      this.isUpload = false;
      this.fileUrl = "";
      console.log(this.dialogStatus);
    },
    // 文件上传前的钩子
    async beforeUpload(file) {
      console.log(file);
      // 拿到文件和文件名
      if (file.raw.type.startsWith("image/")) {
        // this.file = file.raw;
        this.fileName = file.name;
        this.options.img = URL.createObjectURL(file.raw);
        this.dialogStatus.isCropDialogShow = true;
      } else {
        Message.error("请选择图片文件上传！");
        this.fileList = [];
      }

      return false;
    },

    // 移除已选择文件
    handleRemove() {
      this.$refs.uploadRef.clearFiles();
      this.file = "";
      this.dialogData.fileName = "";
      Message.success("移出成功");
    },
    // realTimeCrop() {
    // const that = this
    // that.previewImg = data.url
    // },
    // 完成裁剪
    finishCrop() {
      // getCropData 是获取base64
      this.$refs.cropper.getCropBlob((data) => {
        this.modelSrc = data;
        console.log(data);
        // this.model = false;
        data.lastModifiedDate = new Date(); // 文件最后的修改日期
        const coverFile = new File([data], this.fileName, {
          type: data.type,
          lastModified: Date.now(),
        });
        //裁剪后的图片显示
        // this.options.img = this.modelSrc;
        console.log(coverFile);
        this.file = coverFile;
        // 转化成url展示在前端
        this.fileUrl = URL.createObjectURL(this.file);
        this.dialogStatus.isCropDialogShow = false;
        this.dialogStatus.isSelected = true;
        this.isUpload = false;
        this.dialogStatus.isCrop = true;
      });
    },
    // 上传图片
    async handleUpload() {
      console.log(this.file);
      // 文件转换格式
      const formData = new FormData();
      formData.append("file", this.file);
      const [err, res] = await to(postToOssApi(formData));
      if (!err) {
        console.log(res);
        Message.success("上传成功");
        this.isUpload = true;
        this.dialogData.linkUrl = res.data.url;
      } else {
        this.isUpload = false;
        Message.error("上传失败");
      }
    },
    // 查看图片
    handlePictureCardPreview() {
      this.dialogImageUrl = this.fileUrl;
      this.dialogVisible = true;
    },
    // 关闭预览图片
    handleClosePreview() {
      this.dialogVisible = false;
    },
    // 文件超出一个时调用
    onExceed(fileList, file) {
      Message.error("只能选择一张图片，请先移出后再进行选择！");
      console.log(file, fileList);
    },
  },
  created() {
    this.getList();
  },
};
</script>
